<template>
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input
        placeholder="请你输入SPU名称"
        v-model="spuParams.spuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select v-model="spuParams.tmId">
        <el-option
          v-for="item in allTrademark"
          :key="item.id"
          :value="item.id"
          :label="item.tmName"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        type="textarea"
        placeholder="请你输入SPU描述"
        v-model="spuParams.description"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload
        v-model:file-list="imgList"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :before-upload="handleBeforeUpload"
      >
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img
          w-full
          :src="dialogImageUrl"
          alt="Preview Image"
          style="width: 100%; height: 100%"
        />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <el-select
        v-model="saleAttrIdAndName"
        :placeholder="
          unSelectedSaleAttr?.length > 0
            ? `还有${unSelectedSaleAttr?.length}个销售属性可选择`
            : `暂无销售属性可选择`
        "
      >
        <el-option
          :value="`${item.id}:${item.name}`"
          v-for="item in unSelectedSaleAttr"
          :label="item.name"
          :key="item.id"
        ></el-option>
      </el-select>
      <el-button
        :disabled="!saleAttrIdAndName"
        style="margin: 0 10px"
        type="primary"
        size="default"
        @click="addSaleAttr"
      >
        添加销售属性
      </el-button>
      <el-table border style="margin: 10px 0" :data="saleAttrValue">
        <el-table-column
          type="index"
          align="center"
          label="序号"
          width="80"
        ></el-table-column>
        <el-table-column
          label="销售属性名字"
          width="120"
          prop="saleAttrName"
        ></el-table-column>
        <el-table-column label="销售属性值">
          <template #="{ row }">
            <el-tag
              @close="row.spuSaleAttrValueList.splice(index, 1)"
              v-for="(item, index) in row.spuSaleAttrValueList"
              :key="item.id"
              class="mx-1"
              closable
              style="margin: 0 5px"
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
              @blur="toSaveAttrValue(row)"
              v-model="row.addedAttrValue"
              v-if="row.flag"
              placeholder="请你输入属性值"
              size="small"
              clearable
              style="width: 100px"
            ></el-input>

            <el-button
              v-else
              @click="toAddAttrValue(row)"
              type="primary"
              size="small"
              icon="Plus"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #="{ $index }">
            <el-button
              type="primary"
              size="small"
              @click="saleAttrValue?.splice($index, 1)"
              icon="Delete"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item label="">
      <el-button
        :disabled="!saleAttrValue?.length"
        type="primary"
        size="default"
        @click="save"
      >
        保存
      </el-button>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import {
  reqAllTrademark,
  reqSpuImageList,
  reqSpuSaleAttrList,
  reqAllSpuSale,
  addOrUpdateSpu,
} from '@/api/product/spu/index'
import type {
  AllTrademarkList,
  SpuImgList,
  saleAttrResponseData,
  existedSaleAttrResponse,
  spuData,
  Trademark,
  saleAttr,
  existedSaleAttr,
} from '@/api/product/type'
import { ElMessage } from 'element-plus'
import { ref, computed } from 'vue'
const $emit = defineEmits(['back'])

//所有品牌名称
let allTrademark = ref<Trademark[]>([])
//商品所有照片
let imgList = ref<any>([])
//该商品所有的销售属性值
let saleAttrValue = ref<saleAttr[]>()
//该商品所有的销售属性类型
let allSaleAttr = ref<existedSaleAttr[]>()
//存储SPU对象
let spuParams = ref<spuData>({
  spuName: '',
  description: '',
  category3Id: '',
  tmId: '',
  spuSaleAttrList: [],
  spuImageList: [],
})
//照片墙数据预览相关数据   预览的照片URL和控制dialog的显示与隐藏
let dialogImageUrl = ref<any>()
let dialogVisible = ref<boolean>(false)

//筛选还未选择的属性
let unSelectedSaleAttr = ref<any>([])
unSelectedSaleAttr = computed(() => {
  let unSelectedSale = allSaleAttr.value?.filter((item) => {
    return saleAttrValue.value?.every((item1) => {
      return item1.saleAttrName != item.name
    })
  })
  return unSelectedSale
})

//待添加的属性
let saleAttrIdAndName = ref<string>()

//获取所需的属性  由父组件触发该函数  在下方会将该函数暴露给父组件
const initHasSpuData = async (spu: spuData) => {
  //获取所有品牌名称
  saleAttrIdAndName.value = ''
  spuParams.value = spu
  const result1: AllTrademarkList = await reqAllTrademark()
  //获取该商品所有照片
  const result2: SpuImgList = await reqSpuImageList(spu.id as number)
  //获取该商品所有的销售属性值
  const result3: saleAttrResponseData = await reqSpuSaleAttrList(
    spu.id as number,
  )
  //获取该商品所有的销售属性类型
  const result4: existedSaleAttrResponse = await reqAllSpuSale()

  allTrademark.value = result1.data
  imgList.value = result2.data.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    }
  })
  saleAttrValue.value = result3.data
  allSaleAttr.value = result4.data
}
//点击取消按钮切回数据展示场景卡片
const cancel = () => {
  $emit('back', { num: 0, flag: 0 })
}

//照片墙点击预览图片后的钩子
const handlePictureCardPreview = (uploadFile: any) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

//照片墙上传图片前的钩子  检查图片类型和大小
const handleBeforeUpload = (file: any) => {
  if (
    file.type == 'image/png' ||
    file.type == 'image/gif' ||
    file.type == 'image/jpeg'
  ) {
    if (file.size / 1024 / 1024 < 3) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传的图片大小应小于3MB！',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传的图片类型应为PNG或JPG或GIF',
    })
    return false
  }
}

//添加销售属性方法
const addSaleAttr = () => {
  const arr: any = saleAttrIdAndName.value?.split(':')
  const addedSaleAttr = {
    baseSaleAttrId: arr[0],
    saleAttrName: arr[1],
    spuSaleAttrValueList: [],
  }
  //新增到数组当中
  saleAttrValue.value?.push(addedSaleAttr)
  saleAttrIdAndName.value = ''
}

//添加销售属性值
const toAddAttrValue = (row: saleAttr) => {
  row.flag = true
  row.addedAttrValue = ''
}

//保存新添加的销售属性值
const toSaveAttrValue = (row: saleAttr) => {
  //对象解构赋值
  const { baseSaleAttrId, addedAttrValue } = row
  const newSaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: addedAttrValue as string,
  }

  if ((addedAttrValue as string).trim() == '') {
    ElMessage({
      type: 'error',
      message: '属性值不能为空！',
    })
    return
  }

  const repeat = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName == addedAttrValue
  })
  if (repeat) {
    ElMessage({
      type: 'error',
      message: '属性值重复！',
    })
    return
  }
  //添加到数组当中
  row.spuSaleAttrValueList.push(newSaleAttrValue)
  row.flag = false
}

//点击保存按钮
const save = async () => {
  //保存准备发送post请求的数据
  spuParams.value.spuSaleAttrList = saleAttrValue.value as saleAttr[]
  spuParams.value.spuImageList = imgList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    }
  })

  let result = await addOrUpdateSpu(spuParams.value)

  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: spuParams.value.id ? '修改成功！' : '添加成功！',
    })
    //返回数据展示卡片
    //flag 0 代表修改   1:代表添加
    $emit('back', { num: 0, flag: spuParams.value.id ? 0 : 1 })
  } else {
    ElMessage({
      type: 'error',
      message: spuParams.value.id ? '修改失败！' : '添加失败！',
    })
  }
}

//初始化添加Spu卡片数据
const initAddSpu = async (C3Id: number | string) => {
  //清空数据
  spuParams.value = {
    spuName: '',
    description: '',
    category3Id: '',
    tmId: '',
    spuSaleAttrList: [],
    spuImageList: [],
  }
  imgList.value = []
  saleAttrValue.value = []
  spuParams.value.category3Id = C3Id
  saleAttrIdAndName.value = ''
  const result1: AllTrademarkList = await reqAllTrademark()
  //获取该商品所有的销售属性类型
  const result2: existedSaleAttrResponse = await reqAllSpuSale()
  allTrademark.value = result1.data
  allSaleAttr.value = result2.data
}
//暴露方法给父组件
defineExpose({ initHasSpuData, initAddSpu })
</script>

<style scoped></style>
